package com.lam.common.components.easyexcel.converter;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Objects;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.lam.common.utils.DateUtil;
import com.lam.common.utils.StringUtils;

public class String2DateConverter implements Converter<Date> {

	private Date baseDate = new GregorianCalendar(1900, 0, -1).getTime();

	@Override
	public Class<?> supportJavaTypeKey() {
		return Date.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	/**
	 * 这里读的时候会调用
	 *
	 * @param cellData            NotNull
	 * @param contentProperty     Nullable
	 * @param globalConfiguration NotNull
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Date convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty,
			GlobalConfiguration globalConfiguration) {
		if (CellDataTypeEnum.NUMBER == cellData.getType()) {
			if (cellData.getNumberValue() == null) {
				return null;
			}
			DataFormatData formatData = cellData.getDataFormatData();
			if (StringUtils.isNotBlank(formatData.getFormat())
					&& ("yyyy/m/d".equals(formatData.getFormat())) || ("yyyy-m-d".equals(formatData.getFormat()))) {
				return DateUtil.getDurationDate(baseDate, cellData.getNumberValue().intValue());
			} else {
				return DateUtil.parseSampleDate(Objects.toString(cellData.getNumberValue(), null));
			}
		} else {
			return DateUtil.parseSampleDate(Objects.toString(cellData.getStringValue(), null));
		}
	}

	/**
	 * 这里是写的时候会调用 不用管
	 *
	 * @param value               NotNull
	 * @param contentProperty     Nullable
	 * @param globalConfiguration NotNull
	 * @return
	 */
	@Override
	public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
			GlobalConfiguration globalConfiguration) {
		return new WriteCellData<>(DateUtil.formatDate(value));
	}
}
